﻿(function () {
    'use strict';
    var serviceId = 'safeApply';
    angular.module('app').factory(serviceId, ['$rootScope', safeApply]);

    function safeApply($rootScope) {
        return function($scope, fn) {
            var phase = $scope.$root.$$phase;

            if (phase == '$apply' || phase == '$digest') {
                if (fn) {
                    $scope.$eval(fn);
                }
            }
            else {
                if (fn) {
                    $scope.$apply(fn);
                } else {
                    $scope.$apply();
                }
            }
        };
    }
})();
